import {Button, Card, Col, Dropdown, Empty, message, Popconfirm, Row, Table, Tag} from "antd";
import {DownOutlined, FileTwoTone} from "@ant-design/icons";
import React, {useContext} from "react";
import {hostContext} from "../../store/commonContext.jsx";
import axios from "axios";
import cookie from "js-cookie";

const ChargeTableComponent = ({
                                  downloadFile,
                                  showChargeModel,
                                  showCategoryModel,
                                  handleTableChange,
                                  pagination,
                                  chargeData,
                                  loading,
                                  total
                              }) => {

    const host = useContext(hostContext)
    const year = new Date().getFullYear()
    const token = cookie.get('access_token')
    const userId = cookie.get('user_id')
    const requestHeader = {headers: {'Authorization': 'Bearer ' + token}}

    const onClickDropItem = ({key}) => {
        if ('1' === key) {
            // 年度分类明细报表导出`${host}
            let url = `${host}/charge/export?year=${year}&userId=${userId}`
            let fileName = `${year}年度分类明细.xlsx`
            downloadFile(url, fileName)
        }
    }
    const dropItems = [
        {
            label: '年度分类明细导出',
            key: '1',
            icon: <FileTwoTone/>
        }
    ]
    const menuProps = {
        items: dropItems,
        onClick: onClickDropItem
    }

    const getRowClassName = (record, index) => {
        // 奇偶行不同样式
        let className
        className = index % 2 === 0 ? 'oddRow' : 'evenRow'
        return className
    }

    const getTypeColor = (record) => {
        return record.type === '支出' ? '#f50' : '#2db7f5'
    }

    const getCategoryColor = (record) => {
        // TODO：不知道你想不想要花里花哨的颜色
        // TODO：不知道想不想要可以多选分类，一笔数据有多个分类
    }

    const handleDeleteCharge = async (chargeId) => {
        console.log(chargeId)
        const response = await axios.get(`${host}/charge/delete-charge/${chargeId}`, requestHeader
        )
        if ('200' === response.data.status) {
            message.success('删除成功！')
        }
        setTimeout(() => location.reload(), 500)
    }

    const columns = [
        {
            title: '流水号',
            dataIndex: 'chargeNum',
            key: 'chargeNum',
            width: '12vw',
        },
        {
            title: '种类',
            dataIndex: 'type',
            key: 'type',
            width: '8vw',
            render: (_, record) => (
                <Tag style={{fontSize: 15}} color={getTypeColor(record)}>{record.type}</Tag>
            )
        },
        {
            title: '日期',
            dataIndex: 'date',
            key: 'date',
            width: '8vw'
        },
        {
            title: '金额',
            dataIndex: 'amount',
            key: 'amount',
            width: '8vw',
            render: (text) => `¥ ${Number(text).toLocaleString('en-US')}`
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
            width: '8vw',
            render: (_, record) => (
                <Tag style={{fontSize: 15}} color={getCategoryColor(record)}>{record.category}</Tag>
            )
        },
        {
            title: '备注',
            dataIndex: 'remarks',
            key: 'remarks',
            width: '24vw'
        },
        {
            title: '操作',
            dataIndex: 'options',
            key: 'options',
            render: (_, record) => (
                <Popconfirm
                    title='注意'
                    description='确定要删除吗？一旦删除无法还原。'
                    onConfirm={() => handleDeleteCharge(record.chargeId)}
                    okText='确定'
                    cancelText='取消'
                >
                    <Button
                        key="cancel"
                        danger
                        variant='outlined'
                    >删除
                    </Button>
                </Popconfirm>
            )
        }
    ]

    return (
        <Card style={{marginTop: 4}}>
            <Row gutter={16} align="middle" style={{marginTop: 4, marginBottom: 8}}>
                <Col flex="none">
                    <span>: 收支记录表</span>
                </Col>
                <Col flex="auto" style={{textAlign: 'right'}}>
                    <Dropdown menu={menuProps} placement="bottomRight">
                        <Button style={{marginRight: 8}}>
                            报表导出 <DownOutlined/>
                        </Button>
                    </Dropdown>
                    <Button onClick={showCategoryModel} style={{marginRight: 8}}>
                        配置分类
                    </Button>
                    <Button type="primary" onClick={showChargeModel} style={{marginRight: 8}}>
                        新增记录
                    </Button>
                </Col>
            </Row>
            {total === 0 ? <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="暂无数据"
                    style={{padding: '40px 0'}}
                />
                :
                <Table
                    columns={columns}
                    rowKey="chargeId"
                    loading={loading}
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        pageSizeOptions: ['10', '20', '50'],
                        showTotal: (total) => `共 ${total} 条`,
                        hideOnSinglePage: false,
                        responsive: true
                    }}
                    dataSource={chargeData}
                    onChange={handleTableChange}
                    bordered
                    size="small"
                    locale={{
                        emptyText: (
                            <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description="暂无数据"
                                style={{padding: '40px 0'}}
                            />
                        )
                    }}
                    preserveEmptyBlock
                />
            }
        </Card>
    )
}

export default ChargeTableComponent